package com.dt76.smallloanbackendservice.config;

import com.dt76.smallloanbackendservice.pojo.etao.Employee;
import com.dt76.smallloanbackendservice.pojo.etao.Meun;
import com.dt76.smallloanbackendservice.pojo.etao.Role;
import com.dt76.smallloanbackendservice.service.etao.EmployeeService;
import com.dt76.smallloanbackendservice.service.etao.MenuService;
import com.dt76.smallloanbackendservice.service.etao.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyShiroRealm extends AuthorizingRealm{

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    /* 权限配置 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        System.out.println(employee.geteId()+"-------------员工");
        if (employee != null) {
            //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRole(employee.getRoleStr());
            info.addStringPermissions(employee.getMeuns());
            return info;
        }
        return null;
    }



    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println("验证当前Subject时获取到token为：" + token.toString());
        //查出是否有此用户
        Employee hasEmp = employeeService.getEmpByLoginName(token.getUsername());
        if (hasEmp != null) {
            System.out.println("验证通过");
            Role role = roleService.getRoleById(hasEmp.getRoles().getrId());
            hasEmp.setRoleStr(role.getrName());//获取用户角色
            List<Meun> menus = menuService.getMeunByEmpId(hasEmp.geteId());//获取用户权限
            List<String> menusStrlist=new ArrayList<String>();//用户的权限集合
                for (Meun meun : menus) {
                    if (meun == null) {
                        menusStrlist.add("没有权限");
                    } else {
                        menusStrlist.add(meun.getmName());
                    }
                }
            hasEmp.setMeuns(menusStrlist);

            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
            return new SimpleAuthenticationInfo(hasEmp, hasEmp.getEmpPasswrod(), getName());
        }
        return null;
    }
}
